package com.jdk.learn.juc._07Conditon;

/**
 * Created by ricky
 * on 2018/2/1.
 */

public class CycleExecute {
    private static Object lock = new Object();
    static boolean bool = true;

    public void test() {
        Thread A = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    System.out.print("A");
                    bool = false;
                    //唤醒一个线程
                    lock.notify();
                    try {
                        Thread.sleep(100);
                        //挂起该线程
                        lock.wait();
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                }
            }
        }) ;
        Thread B = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    if (bool) {
                        try {
                            Thread.sleep(100);
                            lock.wait();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }
                    }
                    System.out.print("B");
                    bool = true;
                    lock.notifyAll();
                }
            }
        });
        A.start();
        B.start();
        try {
            A.join();
            B.join();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    public static void main(String[] args) {
       new CycleExecute().test();
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
